package com.supermali.behavior.jump.land;

import com.supermali.behavior.Gravity;
import com.supermali.behavior.down.DownBehavior;
import com.supermali.behavior.jump.JumpBehavior;
import com.supermali.entity.npc.IntesectDirect;
import com.supermali.entity.npc.finish.FinishAbstract;
import com.supermali.entity.npc.person.Person;

import java.util.Set;

public class LandPersonJump extends JumpBehavior {

    private Person person;

    private boolean isOver; // 判断跳跃过程是否结束

    private double totalTime = 0;

    private double v0 = 40; // 初速度

    private boolean isFirst = true;

    public LandPersonJump(Person person) {
        this.person = person;
        isOver = true;
        totalTime = 0;
    }

    @Override
    public void jump() {
        person.setRunState(Person.RunState.Jump);
        isOver = false;
        double dt = 0.04;
        double g = Gravity.g;
        totalTime+=dt;
        double ds = v0 * dt - g * dt * totalTime;
        if(!isFirst) {
            // 碰到障碍物，结束跳跃
            Set<IntesectDirect> intesectDirects = person.checkCollide();
            for (IntesectDirect direct : intesectDirects) {
                // 人物在碰撞物之上
                if(direct.getIntesect() instanceof FinishAbstract){
                    // 结束跳跃
                    isOver = true;
                    totalTime = 0;
                    isFirst=true;
                }else if (direct.getDirect() == IntesectDirect.Direct.TOP) {
                    isOver = true;
                    totalTime = 0;
                    isFirst=true;
                }else if(direct.getDirect()==IntesectDirect.Direct.DOWN){
                    // 结束跳跃
                    isOver = true;
                    totalTime = 0;
                    isFirst=true;
                    double newy = direct.getIntesect().getY()-this.person.getBufferedImage().getHeight()-2;
                    this.person.setY(newy);
                    //人物在碰撞物之下,开启匀加速直线运动 s = v0t+0.5*g*t*t
                    Gravity gravity = this.person.getGravity();
                    double vnew = v0-g*totalTime;
                    gravity.setV0(vnew);
                    gravity.autoDown();
                }
            }
        }
        if(!isOver){
            isFirst = false;
            double y = person.getY();
            person.setY(y + ds);
        }
    }

    public boolean isOver() {
        return isOver;
    }

    @Override
    public void start() {

    }

    @Override
    public void setVy(double vy) {
        this.v0 = vy;
    }
}
